/* component */
import Item from "@gpt/components/prompt-word/item";
/* enum */
import ComponentNameEnum from "@model/enum/ComponentNameEnum";
/* vue */
import { defineComponent, PropType } from "vue";
/* scss */
import "@gpt/components/prompt-word/index.scss";
/* types */
import { SettingGPTPromptWordItem } from "@gpt/types";
import { findComponentsDownward } from "@src/util/assist";

type ItemComponent = InstanceType<typeof Item>

enum SettingGPTPromptWordListEventEnum {
  Change = 'change',
  Click = 'click'
}

export default defineComponent({
  name: ComponentNameEnum.SettingGPTPromptWordList,
  emits: [
    SettingGPTPromptWordListEventEnum.Change,
    SettingGPTPromptWordListEventEnum.Click
  ],
  props: {
    value: {
      type: Array as PropType<SettingGPTPromptWordItem[]>,
      default: () => []
    },
    onChange: {
      type: Function
    }
  },
  data() {
    return {
      
    }
  },
  computed: {
    classNames(): Record<string, boolean> {
      return {
        [ComponentNameEnum.SettingGPTPromptWordList]: true
      }
    }
  },
  methods: {
    emitChangeHandler(value: SettingGPTPromptWordItem[]) {
      this.$emit(SettingGPTPromptWordListEventEnum.Change, value)
    },
    onChangeHandler(value: SettingGPTPromptWordItem, index: number) {
      const list = [...this.value]
      list[index] = value
      this.emitChangeHandler(list)
    },
    onDeleteHandler(index: number) {
      const list = [...this.value]
      list.splice(index, 1)
      this.emitChangeHandler(list)
    },
    validate(): Promise<boolean> {
      const itemsComponents = findComponentsDownward(this, ComponentNameEnum.SettingGPTPromptWordItem) as ItemComponent[]
      return (
        Promise.all(
          itemsComponents.map(itemComponent => {
            return itemComponent.validate()
          })
        ).then((result) => {
          return result.every(Boolean)
        })
      )
    },
    clearValidate() {
      const itemsComponents = findComponentsDownward(this, ComponentNameEnum.SettingGPTPromptWordItem) as ItemComponent[]
      itemsComponents.forEach(itemComponent => {
        itemComponent.clearValidate()
      })
    }
  },
  render() {
    return (
      <div class={this.classNames}>
        {this.value.map((item: SettingGPTPromptWordItem, index: number) => {
          
          const onChangeHandler = (value: SettingGPTPromptWordItem) => {
            this.onChangeHandler(value, index)
          }
          
          const onDeleteHandler = () => {
            this.onDeleteHandler(index)
          }
          
          return (
            <Item
              ref="Item"
              value={item}
              onChange={onChangeHandler}
              onDelete={onDeleteHandler}
            />
          )
          
        })}
      </div>
    )
  }
});